﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using DevExpress.Xpo;
namespace ChuanPlus.DAO
{
    class SampleDAO
    {
        public static void save(Sample sample)
        {
            Session.DefaultSession.BeginTransaction();
            try
            {
                StockCard stCard;
                long idStockCard = StockCardDAO.GenerateId();
                TransactionType tran = TransactionTypeDAO.GetByName("Sample");
                foreach (SampleDetails sampleDetail in sample.SampleDetails)
                {
                    // ================== TRU QUANTITY CUA SAN PHAM THEO SAMPLE DETAIL ===================                        
                        sampleDetail.StockID.QtyBalance -= sampleDetail.Quantity;
                        sampleDetail.StockID.Save();
                    
                    // ================= TAO StockCard CHO TUNG SAN PHAM ================================
                        double Balance = sampleDetail.StockID.QtyBalance;
                        stCard = new StockCard(++idStockCard, sampleDetail.StockID, sample.TakenDate, 0, sampleDetail.Quantity, Balance, tran, sample.SampleID.ToString());
                        stCard.Save();                        
                }
                sample.Status = "P";
                sample.Save();

                Session.DefaultSession.CommitTransaction();
                              
            }
            catch (Exception ex)
            {
                Session.DefaultSession.RollbackTransaction();
                throw new Exception(ex.Message);
            }
        }
        public static List<Sample> getSamples(string status)
        {
            try
            {
                XPQuery<Sample> sample = new XPQuery<Sample>(Session.DefaultSession);
                var list = from s in sample
                           where s.Status == status
                           select s;
                return new List<Sample>(list.AsEnumerable<Sample>());
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
    }
}
